<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本文主要分析Dubbo线程池的构建过程，主要介绍官方文档中有关于ThreadPool的种类：  fixed固定大小线程池，启动时建立线程，不关闭，一致持有。（缺省) cached缓存线程池，空闲一分钟，线程会消费，需要时重新创建新线程。 limited可伸缩线程池，但池中的线程数只会增长不会收缩。 eager优先使用线程来执行新提交任务。（渴望立即执行，而不是进入队列排队执行）。  在介绍这各种线">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo网络通讯篇之NettyServer网络事件之线程池">
<meta property="og:url" content="https://www.codingw.net/posts/25a8fc09.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本文主要分析Dubbo线程池的构建过程，主要介绍官方文档中有关于ThreadPool的种类：  fixed固定大小线程池，启动时建立线程，不关闭，一致持有。（缺省) cached缓存线程池，空闲一分钟，线程会消费，需要时重新创建新线程。 limited可伸缩线程池，但池中的线程数只会增长不会收缩。 eager优先使用线程来执行新提交任务。（渴望立即执行，而不是进入队列排队执行）。  在介绍这各种线">
<meta property="og:locale">
<meta property="article:published_time" content="2020-11-23T09:17:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:10:38.375Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/25a8fc09.html"/>





  <title>源码分析Dubbo网络通讯篇之NettyServer网络事件之线程池 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/25a8fc09.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo网络通讯篇之NettyServer网络事件之线程池</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-23T17:17:01+08:00">
                2020-11-23
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/25a8fc09.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo网络通讯篇之NettyServer网络事件之线程池">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>本文主要分析Dubbo线程池的构建过程，主要介绍官方文档中有关于ThreadPool的种类：</p>
<ul>
<li>fixed<br>固定大小线程池，启动时建立线程，不关闭，一致持有。（缺省)</li>
<li>cached<br>缓存线程池，空闲一分钟，线程会消费，需要时重新创建新线程。</li>
<li>limited<br>可伸缩线程池，但池中的线程数只会增长不会收缩。</li>
<li>eager<br>优先使用线程来执行新提交任务。（渴望立即执行，而不是进入队列排队执行）。</li>
</ul>
<p>在介绍这各种线程策略之前，先简单回顾一下线程池的基本知识。</p>
<span id="more"></span>

<p><strong>线程池的核心属性如下</strong>：</p>
<ul>
<li><p>int corePoolSize<br>线程池核心线程数、常驻线程数。</p>
</li>
<li><p>int maximumPoolSize<br>线程池中最大线程数量</p>
</li>
<li><p>long keepAliveTime<br>线程保持活跃时间,（如果线程创建，并空闲指定值后，线程会被回收，0表示不开启该特性,其范围针对    corePoolSize的线程）</p>
</li>
<li><p>TimeUnit unit<br>keepAliveTime的时间单位。</p>
</li>
<li><p>BlockingQueue&lt; Runnable&gt; workQueue<br>任务队列</p>
</li>
<li><p>ThreadFactory threadFactory<br>线程工厂类，一般通过该线程工厂，为线程命名，以便区分线程。</p>
</li>
<li><p>RejectedExecutionHandler handler)<br>拒绝策略。</p>
</li>
</ul>
<p><strong>提交任务流程（线程创建流程）</strong></p>
<ol>
<li>如果线程池中线程数量小于corePoolSize，则创建一个线程来执行该任务。</li>
<li>如果线程池中的线程大于等于corePoolSize，则尝试将任务放入队列中。</li>
<li>如果成功将任务放入队列，则本次提交任务正常结束，如果放入任务队列失败则继续下一步。<ol start="4">
<li>如果线程池中的线程数量小于最大线程数，则创建先的线程，否则执行拒绝策略。<h2 id="1、fixed-固定大小线程池"><a href="#1、fixed-固定大小线程池" class="headerlink" title="1、fixed 固定大小线程池"></a>1、fixed 固定大小线程池</h2></li>
</ol>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public class FixedThreadPool implements ThreadPool &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public Executor getExecutor(URL url) &#123;</span><br><span class="line">        String name &#x3D; url.getParameter(Constants.THREAD_NAME_KEY, </span><br><span class="line">              Constants.DEFAULT_THREAD_NAME);</span><br><span class="line">        int threads &#x3D; url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);</span><br><span class="line">        int queues &#x3D; url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES);</span><br><span class="line">        return new ThreadPoolExecutor(threads, threads, 0, TimeUnit.MILLISECONDS,</span><br><span class="line">                queues &#x3D;&#x3D; 0 ? new SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                        (queues &lt; 0 ? new LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                                : new LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">                new NamedThreadFactory(name, true), new AbortPolicyWithReport(name,       </span><br><span class="line">                   url));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实现要点：<br>  1、首先获取可配置参数threadname、threads、queues三个参数，分别代表线程池中线程名前缀、线程中最大线程数量、任务队列长度。<br>  2、要实现fixed固定大小线程池，故名思议，就是线程池自创建以来，线程数量始终保持一致。其实现要点是，corePoolSize、maximumPoolSize相等，并且其值等于threads(默认200)，并且keepAliveTime=0，表示线程始终活跃。<br>  3、任务队列，如果queues 为0，则使用SynchronousQueue，如果小于0，则使用无界队列，如果大于0，则创建容量为LinkedBlockingQueue的队列，超过容量，则拒绝入队。<br>  4、线程工厂，NamedThreadFactory，主要设置线程名称，默认为Dubbo-thread-序号。<br>  5、拒绝策略AbortPolicyWithReport，其主要是如果拒绝任务，首先会打印出详细日志，包含线程池的核心参数，并且会dump jstack日志，日志文件默认存储在user.home/Dubbo_JStack.log.timestamp，可以通过dump.directory 属性配置，可通过&lt;  dubbo:protocol&gt; &lt; dubbo:parameter key =“” value = “”/&gt; &lt; /dubbo:protocol&gt;。</p>
<p>这里再简单介绍如果队列长度为0（默认），为什么是选用SynchronousQueue队列。<br><strong>SynchronousQueue的一个简单理解：调用offer、put之前，必须先调用take，也就是先调用take方法的线程阻塞，然后当别的线程调用offer之后，调用take的线程被唤醒，如果没有线程调用take方法，一个线程调用offer方法，则会返回false，并不会将元素添加到SynchronousQueue队列中，因为SynchronousQueue内部的队列长度为0。</strong></p>
<p>与该线程池相关的配置属性：threadname、theadpool、threads、queues。</p>
<h2 id="2、cached-缓存线程池，线程空闲后会被回收"><a href="#2、cached-缓存线程池，线程空闲后会被回收" class="headerlink" title="2、cached   缓存线程池，线程空闲后会被回收"></a>2、cached   缓存线程池，线程空闲后会被回收</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public class CachedThreadPool implements ThreadPool &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public Executor getExecutor(URL url) &#123;</span><br><span class="line">        String name &#x3D; url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME);</span><br><span class="line">        int cores &#x3D; url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS);</span><br><span class="line">        int threads &#x3D; url.getParameter(Constants.THREADS_KEY, Integer.MAX_VALUE);</span><br><span class="line">        int queues &#x3D; url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES);</span><br><span class="line">        int alive &#x3D; url.getParameter(Constants.ALIVE_KEY, Constants.DEFAULT_ALIVE);</span><br><span class="line">        return new ThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS,</span><br><span class="line">                queues &#x3D;&#x3D; 0 ? new SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                        (queues &lt; 0 ? new LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                                : new LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">                new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, url));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>  实现要点：既然要实现线程可以被回收，则必然要设置keepAliveTime。<br>  故对应线程池核心参数设置，对应如下：<br>   ● corePoolSize：通过参数corethreads设置，默认为0<br>   ● maximumPoolSize：通过参数threads设置，默认200<br>   ● keepAliveTime：通过参数alive设置，默认为60 * 1000<br>   ● workQueue  ：通过queues参数设置，默认为0<br>   ● 其他与fixed相同，则不重复介绍</p>
<h2 id="3、limited-可伸缩线程池，其特征：线程数只增不减"><a href="#3、limited-可伸缩线程池，其特征：线程数只增不减" class="headerlink" title="3、limited 可伸缩线程池，其特征：线程数只增不减"></a>3、limited 可伸缩线程池，其特征：线程数只增不减</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public class LimitedThreadPool implements ThreadPool &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public Executor getExecutor(URL url) &#123;</span><br><span class="line">        String name &#x3D; url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME);</span><br><span class="line">        int cores &#x3D; url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS);</span><br><span class="line">        int threads &#x3D; url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);</span><br><span class="line">        int queues &#x3D; url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES);</span><br><span class="line">        return new ThreadPoolExecutor(cores, threads, Long.MAX_VALUE, TimeUnit.MILLISECONDS,</span><br><span class="line">                queues &#x3D;&#x3D; 0 ? new SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                        (queues &lt; 0 ? new LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                                : new LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">                new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, url));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p> 与cached不同的是，limited线程池中线程一旦创建，就不回收，与cached不同的就是keepAliveTime的取值不同，limited取值为：Long.MAX_VALUE,其他与cached相同。</p>
<h2 id="4、eager"><a href="#4、eager" class="headerlink" title="4、eager"></a>4、eager</h2><p>其核心实现主要由TaskQueue、EagerThreadPoolExecutor共同完成。<br>首先，我们关注一下TaskQueued的offer方法。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public boolean offer(Runnable runnable) &#123;</span><br><span class="line">        if (executor &#x3D;&#x3D; null) &#123;</span><br><span class="line">            throw new RejectedExecutionException(&quot;The task queue does not have executor!&quot;);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        int currentPoolThreadSize &#x3D; executor.getPoolSize();     &#x2F;&#x2F; @1</span><br><span class="line">        &#x2F;&#x2F; have free worker. put task into queue to let the worker deal with task.</span><br><span class="line">        if (executor.getSubmittedTaskCount() &lt; currentPoolThreadSize) &#123;   &#x2F;&#x2F; @2</span><br><span class="line">            return super.offer(runnable);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F; return false to let executor create new worker.</span><br><span class="line">        if (currentPoolThreadSize &lt; executor.getMaximumPoolSize()) &#123;    &#x2F;&#x2F; @3</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F; currentPoolThreadSize &gt;&#x3D; max     &#x2F;&#x2F; @4</span><br><span class="line">        return super.offer(runnable); </span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：获取当前线程池中线程的数量。<br>代码@2：如果当前已提交到线程池中的任务数量小于当前存在在的线程数，则走默认的提交流程。<br>代码@3：如果当前已提交到线程中的数量大于当前的线程池，并线程池中数量并未达到线程池允许创建的最大线程数时，则返回false，并不入队，其效果是会创建新的线程来执行。<br>代码@4：如果当前线程池中的线程已达到允许创建的最大线程数后，走默认的提交任务逻辑。<br>其次看一下EagerThreadPoolExecutor#execute</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">public void execute(Runnable command) &#123;</span><br><span class="line">        if (command &#x3D;&#x3D; null) &#123;</span><br><span class="line">            throw new NullPointerException();</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; do not increment in method beforeExecute!</span><br><span class="line">        submittedTaskCount.incrementAndGet();       &#x2F;&#x2F; @1 </span><br><span class="line">        try &#123;</span><br><span class="line">            super.execute(command);</span><br><span class="line">        &#125; catch (RejectedExecutionException rx) &#123;</span><br><span class="line">            &#x2F;&#x2F; retry to offer the task into queue.</span><br><span class="line">            final TaskQueue queue &#x3D; (TaskQueue) super.getQueue();</span><br><span class="line">            try &#123;</span><br><span class="line">                if (!queue.retryOffer(command, 0, TimeUnit.MILLISECONDS)) &#123;</span><br><span class="line">                    submittedTaskCount.decrementAndGet();</span><br><span class="line">                    throw new RejectedExecutionException(&quot;Queue capacity is full.&quot;);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; catch (InterruptedException x) &#123;</span><br><span class="line">                submittedTaskCount.decrementAndGet();</span><br><span class="line">                throw new RejectedExecutionException(x);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Throwable t) &#123;</span><br><span class="line">            &#x2F;&#x2F; decrease any way</span><br><span class="line">            submittedTaskCount.decrementAndGet();   &#x2F;&#x2F; @2</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>其核心实现逻辑：如果提交任务失败，则再走一次默认的任务提交流程。<br>最总后结一下Eager的核心特性。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">public class EagerThreadPool implements ThreadPool &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public Executor getExecutor(URL url) &#123;</span><br><span class="line">        String name &#x3D; url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME);</span><br><span class="line">        int cores &#x3D; url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS);</span><br><span class="line">        int threads &#x3D; url.getParameter(Constants.THREADS_KEY, Integer.MAX_VALUE);</span><br><span class="line">        int queues &#x3D; url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES);</span><br><span class="line">        int alive &#x3D; url.getParameter(Constants.ALIVE_KEY, Constants.DEFAULT_ALIVE);</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F; init queue and executor</span><br><span class="line">        TaskQueue&lt;Runnable&gt; taskQueue &#x3D; new TaskQueue&lt;Runnable&gt;(queues &lt;&#x3D; 0 ? 1 : queues);</span><br><span class="line">        EagerThreadPoolExecutor executor &#x3D; new EagerThreadPoolExecutor(cores,</span><br><span class="line">                threads,</span><br><span class="line">                alive,</span><br><span class="line">                TimeUnit.MILLISECONDS,</span><br><span class="line">                taskQueue,</span><br><span class="line">                new NamedThreadFactory(name, true),</span><br><span class="line">                new AbortPolicyWithReport(name, url));</span><br><span class="line">        taskQueue.setExecutor(executor);</span><br><span class="line">        return executor;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其核心特性如下：<br>1、首先，其配置参数与cached类型的线程池相同，说明eager也是基于缓存的。<br>2、eager与cached类型线程池不同的一点是，提交任务后，线程优先于队列，默认的提交流程是如果线程数达到核心线程数后，新提交的任务是首先进入队列，但eager是优先创建线程来执行，这有点与公平锁，非公平锁一样的概念了。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/caabd6c1.html" rel="next" title="源码分析Dubbo序列化-源码分析kryo各数据类型的序列化编码机制">
                <i class="fa fa-chevron-left"></i> 源码分析Dubbo序列化-源码分析kryo各数据类型的序列化编码机制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/dff42af6.html" rel="prev" title="源码分析Dubbo网络通讯篇之NettyServer网络事件派发机制(Dispatch)">
                源码分析Dubbo网络通讯篇之NettyServer网络事件派发机制(Dispatch) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81fixed-%E5%9B%BA%E5%AE%9A%E5%A4%A7%E5%B0%8F%E7%BA%BF%E7%A8%8B%E6%B1%A0"><span class="nav-number">1.</span> <span class="nav-text">1、fixed 固定大小线程池</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81cached-%E7%BC%93%E5%AD%98%E7%BA%BF%E7%A8%8B%E6%B1%A0%EF%BC%8C%E7%BA%BF%E7%A8%8B%E7%A9%BA%E9%97%B2%E5%90%8E%E4%BC%9A%E8%A2%AB%E5%9B%9E%E6%94%B6"><span class="nav-number">2.</span> <span class="nav-text">2、cached   缓存线程池，线程空闲后会被回收</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81limited-%E5%8F%AF%E4%BC%B8%E7%BC%A9%E7%BA%BF%E7%A8%8B%E6%B1%A0%EF%BC%8C%E5%85%B6%E7%89%B9%E5%BE%81%EF%BC%9A%E7%BA%BF%E7%A8%8B%E6%95%B0%E5%8F%AA%E5%A2%9E%E4%B8%8D%E5%87%8F"><span class="nav-number">3.</span> <span class="nav-text">3、limited 可伸缩线程池，其特征：线程数只增不减</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4%E3%80%81eager"><span class="nav-number">4.</span> <span class="nav-text">4、eager</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
